/*
 *  Copyright 2010 Massimiliano Mazzarolo
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0
 *        
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package grails.coherence

import com.tangosol.util.Filter
import com.tangosol.util.filter.AllFilter
import com.tangosol.util.filter.AnyFilter
import groovy.lang.Delegate
import grails.coherence.exceptions.MalformedFilterException

/**
 * Holder container for filters.
 * 
 * @author Massimiliano Mazzarolo
 * @since 0.1
 *
 */
class MultiFilterContainer extends ArrayList {
  
  public static final String AND = 'and'
  public static final String OR = 'or'
  public static final String SINGLE = 'single'  

  String type

  public Filter process() {
    def filters = create()
    switch (type) {
      case AND:
        return new AllFilter(filters)
        break
      case OR:
        return new AnyFilter(filters)
        break
      case SINGLE:
        if (filters.length > 1) {
          throw new MalformedFilterException("Invalid filters chain: found ${filters.length} filters while expecting once only. Subchains was: ${this}")
        }
        return filters[0]
    }
  }

  private Filter[] create() {

    def filters = []

    this.each {el ->
      if (el instanceof MultiFilterContainer) {
        filters << el.process()
      } else {
        filters << el
      }
    }
    return filters.toArray(new Filter[filters.size()])
  }
}